package farmer.core;

import pathfinding.grid.GridLocation;
import pathfinding.grid.GridPath;

import java.awt.Graphics2D;

import core.util.Useful;

import farmer.render.building.Map;

public class Unit extends Basic implements Drawable, Updateable{

	protected double posX;
	protected double posY;
	protected int size;
	protected boolean isSelected;
	protected GridPath path;
	protected GridLocation nextLoc;
	protected double speed = 0.1;
	
	public Unit(int x, int y){
		posX = x*Map.cellWidth+14;
		posY = y*Map.cellWidth+14;
		size = Map.unitCellWidth;
	}
	
	public boolean contains(int x, int y){
		if((posX <=x && posX+size >= x) && (posY <= y && posY+size >= y)){
			return true;
		}
		return false;
	}
	
	public void setPath(GridPath path){
		this.path = path;
		if(path != null && path.hasNextMove()){
			nextLoc = path.getNextMove();
		}
		if(path != null && path.hasNextMove()){
			nextLoc = path.getNextMove();
		}
	}
	
	public void setSelected(boolean value){
		isSelected = value;
	}
	
	public int getX(){
		return (int) posX;
	}
	public int getY(){
		return (int) posY;
	}
	public int getSize(){
		return size;
	}
	
	@Override
	public void update(int deltaTime) {
		moveToNextLoc(deltaTime);
	}
	
	private void moveToNextLoc(int deltaTime){
		if(nextLoc != null){
			int endX = nextLoc.getX()*Map.unitCellWidth;
			int endY = nextLoc.getY()*Map.unitCellWidth;
			double dx = endX-posX;
			double dy = endY-posY;
			double dist = dx*dx + dy*dy;
			double minDist = deltaTime*speed*deltaTime*speed;
			if(dist < minDist){
				if(path != null && path.hasNextMove()){
					//Select the next location
					nextLoc = path.getNextMove();
					moveToNextLoc(deltaTime);
				}else{
					//No next location -- EXIT
					posX = endX;
					posY = endY;
					nextLoc = null;
					path = null;
				}
			}else{
				//Move toward the next location
				double angle = Useful.findAngle(endX-posX, endY-posY);
				dx = Math.cos(angle)*speed*deltaTime/nextLoc.getValue();
				dy = Math.sin(angle)*speed*deltaTime/nextLoc.getValue();
				posX += dx;
				posY += dy;
			}
		}
	}

	@Override
	public void draw(Graphics2D g) {
		// TODO Auto-generated method stub
		
	}

}
